<template>
  <div class="app-projectinfo-form">
    <i-form>
      <app-form-item class="ml-2 mt-3 mr-2">
        <el-input
          v-model="form.name"
          placeholder="输入标题，回车创建"
          @input="onChangeName"
        ></el-input>
        <div style="font-size:10px;color:red" class="ml-6">{{ taskName }}</div>
      </app-form-item>

      <app-form-item>
        <i class="fa fa-user fa-lg fa-fw"></i>
        <el-dropdown
          trigger="click"
          placement="bottom-start"
          @command="handleCommandPrincipal"
          class="ml-1"
          style="transform: translateY(2px);"
        >
          <div>
            <el-tag
              closable
              type="info"
              v-if="form.assignedto"
              class="assignedto-tag"
              @close="handleClose()"
            >
              {{ tagname }}
            </el-tag>
            <span class="el-dropdown-link" v-else>
              请选择负责人
            </span>
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="item in taskTeamMemberMetaShow"
              :key="item.value"
              :command="{ account: item.value, realname: item.label }"
            >
              <div v-if="item.value != 0">
                <v-list-item-avatar
                  color="#81D4FA"
                  size="18"
                  style="transform: translateY(-1px);margin-right: 7px"
                >
                  <span style="color:white;font-size:1px;">
                    {{
                      item.label
                        ? item.label.substr(item.label.length - 1)
                        : item.value.substr(item.value.length - 1)
                    }}
                  </span>
                </v-list-item-avatar>
                {{ item.label ? item.label : item.value }}
              </div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </app-form-item>

      <app-form-item>
        <i class="fa fa-calendar-check-o fa-lg  fa-fw"></i>

        <el-date-picker
          value-format="yyyy-MM-dd"
          v-model="form.deadline"
          type="date"
          placeholder="选择截止日期"
          width="155px"
          class="pickerOptions"
          :picker-options="expireTimeOption"
        ></el-date-picker>
      </app-form-item>

      <app-form-item class="mb-1 mt-2">
        <i class="fa fa-warning fa-lg fa-fw"></i>

        <el-dropdown
          trigger="click"
          placement="bottom-start"
          :class="['taskPriName']"
          @command="handleCommandPri"
        >
          <span
            :class="['el-dropdown-link']"
            :style="{
              'background-color':
                form.pri == 1
                  ? 'red'
                  : form.pri == 2
                  ? 'yellow'
                  : form.pri == 3
                  ? '#9E9E9E'
                  : form.pri == 4
                  ? 'green'
                  : '#9E9E9E',
            }"
          >
            {{ priname }}
          </span>

          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="item in priMetaShow"
              :key="item.value"
              :command="{ pri: item.value, priname: item.label }"
            >
              <div
                class="pri-itemicon"
                :style="
                  'margin: 5px 5px;border-radius: 25%;width: 25px; height: 25px; float: left; background:' +
                    item.color
                "
              ></div>
              <span
                class="pri-itemtext"
                style="color: #8492a6; font-size: 13px"
                >{{ item.label }}</span
              >
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </app-form-item>

      <app-form-item class="mb-2">
        <i class="fa fa-tags fa-lg fa-fw"></i>
       
        <el-dropdown
          trigger="click"
          placement="bottom-start"
          class="select-type ml-1"
          style="transform: translateY(2px);"
          @command="handleCommandType"
        >
          <span
            :class="['el-dropdown-link',typetext?'typeText':'']"
            :style="{'background-color':typetext?typeColor:''}"
          >
          {{typetext?typetext:'添加任务类型'}}
          </span>

          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="item in typeMetaShow"
              :key="item.value"
              :command="{ type: item.value, typeText: item.label,typeColor:item.color }"
            >
              
              <span
                  :style="{'font-size': '13px','border-radius': '16px','padding': '0 6px'}"
                  ><v-icon size="14" :color="form.type == item.value?item.color:''">fa fa-check-square-o</v-icon>{{ item.label }}</span
                >
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </app-form-item>

      <app-form-item class="select-item">
        <i class="fa fa-file-text-o fa-lg fa-fw" style="float:left"></i>
        <div
          v-show="!isTaskDetailEdit"
          @click="taskDetailEditStatus()"
          style="float:left;transform: translateY(-6px);"
          class="adddesc"
        >
          <span>添加任务描述</span>
        </div>
        <app-richtexteditor-comment
          :value="form.desc ? form.desc : ''"
          :data="JSON.stringify({ data: '1' })"
          @change="
            (val) => {
              taskDetailRichTextChange(val);
            }
          "
          ref="taskDetailRichtext"
          :height="266"
          placeholder="添加任务描述"
          name="discuss"
          :uploadparams="{ objecttype: 'task', version: 'editor' }"
          :exportparams="{ objecttype: 'task', version: 'editor' }"
          style="float:left;width:calc( 100% - 30px )"
          v-show="isTaskDetailEdit"
        >
        </app-richtexteditor-comment>
      </app-form-item>
      <app-form-item>
        <v-btn
          depressed
          small
          class="ml-5 mr-2 mt-4"
          style="background-color:#44acb6;color:white;"
          @click="createTask()"
        >
          创建任务
        </v-btn>

        <v-btn depressed color="white" small @click="closeform()" class="mt-4">
          取消
        </v-btn>
      </app-form-item>
    </i-form>
  </div>
</template>

<script lang="ts">
import {
  Vue,
  Component,
  Prop,
  Model,
  Emit,
  Watch,
  Provide,
} from "vue-property-decorator";

import "./app-projectinfo-form.less";
import { Environment } from "@/environments/environment";
import TaskService from "@service/task/task-service";
import ProjectService from "@/service/project/project-service";

@Component({})
export default class AppProjectinfoForm extends Vue {
  /**
   * 实体服务对象
   *
   * @type {TaskService}
   * @memberof AppProjectinfoForm
   */
  public appEntityService: TaskService = new TaskService();

  /**
   * form表单
   *
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  public form: any = {
    name: "",
    assignedto: "",
    deadline: "",
    pri: "3",
    type:"",
    desc: "",
    project: "",
    projectname: "",
  };

  /**
   * 空Form
   *
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  public emptyform: any = {
    name: "",
    assignedto: "",
    deadline: "",
    pri: "3",
    type:"",
    desc: "",
    project: "",
    projectname: "",
  };

  /**
   * 默认级别name
   *
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  public priname: any = "普通";

  /**
   * 显示类型名称
   * 
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  public typetext: any = "";

  /**
   * 类型颜色
   *
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  public typeColor: any = "";


  /**
   * 显示下载所有附件
   *
   * @type {boolean}
   * @memberof AppProjectinfoForm
   */
  public showDownloadAllFiles: boolean = false;

  /**
   * 设置日期选择器不能选择以往的日期
   *
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  public expireTimeOption: any = {
    disabledDate(date: any) {
      //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
      return date.getTime() < Date.now() - 8.64e7;
    },
  };

  /**
   * 任务区域 是否正在编辑
   *
   * @type {boolean}
   * @memberof AppProjectinfoForm
   */
  public isTaskDetailEdit: boolean = false;

  /**
   * 选择负责人
   *
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  public tagname: any = "";

  /**
   * 上下文
   *
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  @Prop() public context: any;

  /**
   * 视图参数
   *
   * @type {*}
   * @memberof AppProjectinfoForm
   */
  @Prop() public viewparams: any;

  /**
   * 优先级代码项
   *
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  public priMetaShow: any = [];

  /**
   * 文件列表
   *
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  public fileList: any = [];

  /**
   * 当前项目下的团队列表
   *
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  @Prop() public taskTeamMemberMetaShow: any;

  /**
   * 所有用户信息
   *
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  @Prop() public userslist: any;

  /**
   * 任务类型列表
   * 
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  @Prop() public typeMetaShow:any;

  /**
   * 项目信息
   *
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  public projectData: any = {};

  /**
   * 上传路径
   * @type {string}
   * @memberof AppProjectinfoForm
   */
  public uploadUrl: string = Environment.BaseUrl + Environment.UploadFile;

  /**
   * 导出文件路径
   * @type {string}
   * @memberof AppProjectinfoForm
   */
  public exportFileUrl: string = Environment.BaseUrl + Environment.ExportFile;

  /**
   * 优先级修改，更新任务
   *
   * @param {any} val
   * @memberof AppProjectinfoForm
   */
  public priorityChange(val: any) {
    // console.log(val);
    this.form.pri = val;
  }

  /**
   * 文件移除
   *
   * @param {any} file
   * @param {any} fileList
   * @memberof AppProjectinfoForm
   */
  public handleRemove(file: any, fileList: any) {}

  /**
   * 实体服务对象
   *
   * @type {ProjectService}
   * @memberof AppProjectinfoForm
   */
  public appProjectService: ProjectService = new ProjectService({
    $store: this.$store,
  });

  /**
   * Vue声明周期，组件创建完毕
   *
   * @memberof AppProjectinfoForm
   */
  public created() {
    // 优先级代码表
    let pritCodelist = this.getpritCodelist();
    this.priMetaShow = pritCodelist;
    this.getProject();
  }
  /**
   * 任务描述值变化
   *
   * @param {any} val
   * @memberof AppProjectinfoForm
   */
  public taskDetailRichTextChange(val: any) {
    this.form.desc = val;
  }

  /**
   * input失去焦点事件
   *
   * @param {any} event
   * @memberof AppProjectinfoForm
   */
  public onChangeName(event: any) {
    if (this.form.name) {
      this.taskName = "";
    }
  }

  /**
   * 移除之前
   *
   * @param {any} file
   * @param {any} fileList
   * @memberof AppProjectinfoForm
   */
  public beforeRemove(file: any, fileList: any) {
    return this.$confirm(`确定移除 ${file.name}？`, "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      let fileid = file.fileid;
      if (!fileid) {
        fileid = file.response.id;
      }
      if (!fileid) {
        return false;
      }
      return new Promise((resolve: any, reject: any) => {
        let context = { fileid: fileid };
        let result: Promise<any> = this.appEntityService.deleteFileList(
          context,
          {},
          true
        );
        result
          .then((response) => {
            if (response && response.status === 200) {
              console.log("删除成功");
              resolve(true);
            }
          })
          .catch((response) => {
            this.$Notice.error({ title: "错误", desc: response.data.detail });
            reject(false);
          });
      });
    });
  }

  /**
   * 选择优先级
   *
   * @param {any} command
   * @memberof AppProjectinfoForm
   */
  public handleCommandPri(command: any) {
    this.priname = command.priname;
    Object.assign(this.form, { pri: command.pri });
  }

  /**
   * 选择类型
   * 
   * @param {ant} command
   * @memberof AppProjectinfoForm
   */
  public handleCommandType(command: any){
    this.typetext = command.typeText;
    this.typeColor = command.typeColor;
    Object.assign(this.form,{type: command.type});
  }

  /**
   * el-file 文件状态改变时
   *
   * @param {file, filelist}
   * @memberof AppProjectinfoForm
   */
  public handleChange(file: any, fileList: any) {
    this.fileList = fileList;
    this.showDownloadAllFiles = this.fileList.length > 1;
    this.$forceUpdate();
  }

  /**
   * 点击文件（下载）
   *
   * @param {any} file
   * @memberof AppProjectinfoForm
   */
  public handlePreview(file: any) {
    let fileid = file.fileid;
    if (fileid) {
      window.open(`${this.exportFileUrl}/${fileid}`);
    } else {
      fileid = file.response.id;
      if (fileid) {
        window.open(`${this.exportFileUrl}/${fileid}`);
      }
    }
  }

  /**
   * 获取项目信息
   *
   * @memberof AppProjectinfoForm
   */
  public getProject() {
    const context: any = JSON.parse(JSON.stringify(this.context));
    const get: Promise<any> = this.appProjectService.Get(context, {}, true);
    return new Promise((resolve: any, reject: any) => {
      get.then((response: any) => {
        if (response && response.status === 200) {
          let data = response.data;
          let dynamicForm = {project:data.id,projectname:data.name}
          Object.assign(this.form, dynamicForm);
          Object.assign(this.emptyform, dynamicForm);
        }
      });
    });
  }

  /**
   * 选择负责人
   *
   * @param {any} command
   * @memberof AppProjectinfoForm
   */
  public handleCommandPrincipal(command: any) {
    Object.assign(this.form, { assignedto: command.account });
    //this.form.assignedto = command.acount;
    this.tagname = command.realname;
    this.$forceUpdate();
  }

  /**
   * 关闭表单
   *
   * @memberof AppProjectinfoForm
   */
  public handleClose() {
    Object.assign(this.form, { assignedto: "" });
    this.$forceUpdate();
  }

  /**
   * 获取优先级代码表
   *
   * @memberof AppProjectinfoForm
   */
  public getpritCodelist() {
    const codelist = this.$store.getters.getCodeList("Task__pri");
    if (codelist) {
      let items: Array<any> = [...JSON.parse(JSON.stringify(codelist.items))];
      return items;
    } else {
      console.log(`----Action__type----代码表不存在`);
      return [];
    }
  }

  /**
   * 任务区域 编辑、保存、取消 点击事件
   *
   * @memberof AppProjectinfoForm
   */
  public taskDetailEditStatus() {
    // 编辑状态改变
    this.isTaskDetailEdit = !this.isTaskDetailEdit;
  }

  /**
   * 提示用户输入任务名称标题
   *
   * @type {any}
   * @memberof AppProjectinfoForm
   */
  public taskName: any = "";

  /**
   * 创建任务事件
   *
   * @memberof AppProjectinfoForm
   */
  public createTask() {
    if (!this.form.name) {
      this.taskName = "请输入任务名称";
      return;
    }

    let isloading = true;
    return new Promise((resolve: any, reject: any) => {
      let result: Promise<any>;
      result = this.appEntityService.Create({}, this.form, isloading);
      result.then((response: any) => {
        if (response && response.status === 200) {
          this.$emit("createTask", JSON.parse(JSON.stringify(response.data)));
          Object.assign(this.form,this.emptyform);
          this.typetext = "";
          this.priname = "普通";
          this.isTaskDetailEdit = !this.isTaskDetailEdit;
        }
      }).catch((response) => {
          if (response && response.status === 500) {
            this.$Notice.error({ title: "错误", desc: response.data.message });
            reject(response);
          }
        });
    });
  }
  /**
   * 关闭表单
   *
   *@memberof AppProjectinfoForm
   */
  public closeform() {
    Object.assign(this.form,this.emptyform);
    this.taskName = "";
    this.typetext = "";
    this.priname = "普通";
    this.isTaskDetailEdit = false;
    this.$emit("changedisplaymodel", {});
  }
}
</script>
